2014-10-17 430 views
2

const std :: string賦值/聲明中最適合什麼?使用構造函數(例如,const std::string WORD("hello");)或使用相等的運算符(例如const std::string WORD= "hello";)? 這些東西在內存使用情況或時間流程上有差異嗎?C++ const std :: string賦值

+0

在這裏試一試並比較生成的程序集http://gcc.godbolt.org/ – 2014-10-17 02:21:58

+0

兩者都使用構造函數。在你顯示的代碼中沒有賦值,也沒有'operator ='。 – chris 2014-10-17 02:40:33

+0

[複製初始化和直接初始化之間C++有差異嗎?](http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization- and-direct-initializati) – Galik 2014-10-17 03:12:40

回答

2

對於任何合理的編譯器,生成的代碼在兩種情況下都是相同的。在這種情況下是否應該使用直接初始化或複製初始化基本上是基於意見的。

0

在這兩種情況下,通常編譯器都會使用"Return Value Optimisation"刪除副本。查看ideone here調用該代碼既不是普通的構造函數,也沒有賦值運算符,因爲它不打印他們被調用屏幕:

即:

#include <iostream> 

class C 
{ 
    public: 
    C() {} 
    C(const char[]) { std::cout << "Ordinary Constructor" << std::endl; } 
    C& operator=(const char[]) { std::cout << "Assignment Operator" << std::endl; return *this; } 
}; 

int main() { 
    std::cout << "Start" << std::endl; 
    C x1 = "Hello"; 
    C x2("Hello"); 
    std::cout << "End" << std::endl; 
} 

只是輸出:

Start 
End 

它不輸出:

Start 
Assignment Operator 
Ordinary Constructor 
End 

由於C + +允許跳過副本並臨時構建到位。

+1

它不會在這裏調用賦值操作符,因爲x1和x2都被初始化,它們不被賦值。 – kraskevich 2014-10-17 03:33:38

+0

'C x1 =「Hello」;'表示拷貝構造函數,不是賦值操作符 – 2014-10-17 03:39:25

0

的線條:

std::string x = "hello"; 
std::string x("hello"); 

都只會調用std::string構造。也就是說,它們是相同的,都不會使用operator=重載。

相關問題