36得票1回答
C++中括号的类型如何影响对象的生命周期?

我的一个朋友向我展示了一款使用C++20编写的程序: #include <iostream> struct A { A() {std::cout << "A()\n";} ~A() {std::cout << "~A()\n";} }; ...

29得票3回答
在同一表达式中,两个临时变量的地址是否保证不同?

考虑下面的程序:#include <iostream> int const * f(int const &i) { return &i; } int main() { std::cout << f(42); // #1 std:...

28得票5回答
临时对象何时被销毁?

以下代码会输出one, two, three。这是所有C++编译器都期望的且正确的吗? class Foo { const char* m_name; public: Foo(const char* name) : m_name(name) {} ~Foo(...

26得票2回答
非常量引用绑定到临时对象,是Visual Studio的bug吗?

在编译一些可移植代码时,我遇到了这个问题,使用gcc编译会出现奇怪的错误。然而这段奇怪的代码可以在Visual Studio中编译通过,真的让我大吃一惊:class Zebra {int x;}; Zebra goo() {Zebra z; return z;} void foo(Zebra ...

25得票7回答
在for循环中,pIter != cont.end()的性能表现问题

I was getting through "Exceptional C++" by Herb Sutter lately, and I have serious doubts about a particular recommendation he gives in Item 6 - Tem...

24得票2回答
对临时变量的const引用与返回值优化

我知道将一个右值分配给一个常量左值引用会延长临时对象的生命周期直到作用域结束。但是,什么情况下需要使用这种方法,什么情况下应该依赖返回值优化并不是很清楚。LargeObject lofactory( ... ) { // construct a LargeObject in a wa...

23得票1回答
从临时变量中获取引用在C++代码中是否有效?

我使用了以下语法糖: for (auto& numberString: {"one", "two", "three", "four"}) { /* ... */} 这段代码是否有效?据我所知,根据这个问题,它应该是不合法的,但是代码的运行结果却与预期相符。我认为自己对这个问题的理...

21得票1回答
在参数列表中构造一个对象并将对象的内部数据的指针传递给函数,这样做安全吗?

下面的C++代码是否格式良好?std::string会在函数执行完毕之前还是之后被销毁? void my_function(const char*); ... my_function(std::string("Something").c_str()); 我知道我可以这样做my_fun...

20得票2回答
寿命延长和条件运算符

本地的左值引用(指向常量)和右值引用可以延长临时对象的生命周期:const std::string& a = std::string("hello"); std::string&& b = std::string("world"); 如果初始化不是简单表达式,而是使用条...

20得票4回答
临时对象存储在哪里?

暂时对象是否存储在动态(堆)内存中?(参考链接)