簡體   English   中英

返回子對象時,為什么延長了“子對象的完整對象”對象的壽命?

[英]Why is the lifetime of an object “that is the complete object of a subobject” extended when the subobject is returned?

我正在研究綁定到const &時的臨時生存期的延長,並且我想了解以下情況:

#include <string>
#include <iostream>

char const * foo()
{
    std::string s("tmp");
    return s.c_str();
}

int main()
{
    char const * const & p = foo();

    // Why is the lifetime of the std::string extended in the following line,
    // rather than just the lifetime of the char* itself?
    std::cout << p; // This prints 'tmp' in VS2013
}

如前所述,在Visual Studio 2013中,代碼會正確生成,並且控制台顯示tmp

這對我來說很奇怪,因為延長生命周期的對象是被調用函數局部對象的子對象 ,該對象在退出該函數時被銷毀。 堆棧上沒有std::string作為返回值,它的壽命可以由編譯器在編譯main函數時進行擴展-只有char *返回值,其壽命可以延長,但將是一個懸空的指針。

但顯然,使用壽命正在延長!

我發現的最接近的問題是: “ T const&t = C()。a;”嗎? 延長“ a”的壽命? ...但是,在這個問題中,代碼B const& b = A().b; 在調用函數內部引用堆棧上的完整對象A ,因此可以延長對象的生命周期。

如前所述,在我看來,應該在我的代碼示例中延長其生存期的對象是char * ,而不是char * points的字符串。 (也就是說,我認為返回值只是一個char *的大小,它的使用期限會延長,但它將變成一個懸空的指針。)

我不明白如何在上述示例代碼中延長std::string的生命周期。 有人可以解釋為什么這滿足通過char const * const &延長std::string的生存期,而不只是延長char *的生存期的條件嗎?

如何遵循對象的構造函數和析構函數

#include <string>
#include <iostream>

class string_like: public std::string {

public:
  string_like(const char* str): std::string (str) {
    std::cout << "string_like() : \n";
}
  ~string_like() {
    std::cout << "~string_like(): \n";
}
};

char const * foo()
{
  std::cout << "in foo(){} : \n" ;

  string_like  s("tmp");

  std::cout << "leaving foo(){}" << "\n";
  return s.c_str();
}


int main()
{
  std::cout << "begin main()\n";
  std::cout << "calling foo() :" << "\n";
  char const * const & p = foo();
  std::cout << "after calling foo() :\n";
  std::cout << "still in main\n" ;
  std::cout << p << "\n"; // print using g++
  std::cout << "leave main()\n";

}

我通過g ++得到以下輸出:

begin main()
calling foo() :
in foo(){} : 
string_like() :
leaving foo(){}
~string_like():  object is destroyed here
after calling foo() :
still in main
tmp    
leave main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM