如我错了请纠正我.说我有:
struct X
{
std::string mem_name;
X(std::string name)
: mem_name(std::move(name))
{}
...
};
struct Y
{
std::string mem_name;
Y(const std::string &name)
: mem_name(name)
{}
...
};
Run Code Online (Sandbox Code Playgroud)
在X
ctor中,name
显然是传递给任何参数的副本X
,X
调用std::string
初始化的移动mem_name
,对吧?
让我们称之为X*的复制然后移动 ; 两个操作:COPY,MOVE.
在Y
's ctor中,name
是一个const ref,这意味着没有元素的实际副本,因为我们直接处理从Y
需要创建对象的地方传递的参数.但是,我们复制name
到初始化mem_name
的Y
; 一个操作:COPY.因此它应该更快(对我来说更好)?
在Scott Meyer的GN13演讲中(围绕时间框架8:10和8:56),他谈到了"想要速度?通过价值传递",我想知道在传递参数时是否有任何性能差异或损失(或者字符串是准确的)通过引用和传递值"以获得速度?"
我知道按值传递参数可能很昂贵,特别是在处理大数据时.
也许(显然?)我的谈话中缺少一些东西?
在测试某些功能的同时std::thread
,一位朋友遇到了GCC的问题,我们认为值得问一下这是否是GCC错误或者这个代码可能有问题(代码打印(例如)"7 8 9 10 1 2 3" ,但我们希望打印[1,10]中的每个整数:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <thread>
int main() {
int arr[10];
std::iota(std::begin(arr), std::end(arr), 1);
using itr_t = decltype(std::begin(arr));
// the function that will display each element
auto f = [] (itr_t first, itr_t last) {
while (first != last) std::cout<<*(first++)<<' ';};
// we have 3 threads so we need to figure out the ranges for each thread to show
int increment = std::distance(std::begin(arr), std::end(arr)) / 3;
auto first …
Run Code Online (Sandbox Code Playgroud) 我最近正在编写一个代码,我偶然发现了GCC和Clang中的一些不寻常的东西.使用brace-init会在gcc中触发编译错误,而直接初始化则会&b = a
起作用.下面的代码是我遇到的那种行为的一个非常简单的例子,我想知道为什么GCC不编译代码,因为shared_ptr都没有采用initializer_list而且a
是一个左值
#include <iostream>
#include <memory>
int main( )
{
std::shared_ptr<int> a { nullptr }, &b { a };
a = std::make_shared<int> ( 1e3 );
std::cout << ( b ? *b : 0 ) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Clang 3.4编译了这个,但GCC 4.8没有编译.
我正在尝试为移动电话开发Qt应用程序,因此我决定不使用任何标准库(因为我担心某些平台可能尚未得到支持).所以,我不得不重新实现智能指针包装器(当然使用标准草案),没有任何标准头文件.在Qt中,有一些Widgets,例如QMenu和QToolBar,当需要创建时 - 它是这样创建的
QMenu *mainMenu = new QMenu;
QToolBar *toolBar = new QToolBar;
//To add a new menu bar or ToolBar, we do
mainMenu = menuBar()->addMenu("&File");
//add all the elements to the first menuBar
mainMenu->addAction(QAction { });
mainMenu = menuBar()->addMenu("&Edit"); //for second Menu
//same goes for QToolBar
Run Code Online (Sandbox Code Playgroud)
我实现unique_ptr"观察者"的唯一方法是使用get(),operator*和operator->成员函数来访问底层成员.显而易见的是,MenuBar() - > addNew()返回一个指向另一个mainMenu的新指针.现在我的问题是,旧指针会发生什么?什么跟踪他们?如何使用智能指针代替这些裸指针,或者我必须坚持使用严格使用裸指针的"老方法"?
注意:所有文件都可以在这里找到
我的一些同事今天进行了辩论,我想澄清一下.它是关于表达式中的评估顺序和序列点.标准中明确指出,C/C++在表达式中没有从左到右的评估,这与Java之类的语言不同,后者保证具有从左到右的顺序.因此,在下面的表达式中,在评估最右边的操作数(C)之前,对二进制操作中最左边的操作数(B)的求值进行排序:
A = B B_OP C
Run Code Online (Sandbox Code Playgroud)
根据序列前序列(Undefined Behavior)和Bjarne的TCPPL 3rd ed 下的CPPReference,下面的表达式是UB
x = x++ + 1;
Run Code Online (Sandbox Code Playgroud)
它可以被解释为像BUT这样的编译器,据说下面的表达式在C++ 11中显然是一个明确定义的行为
x = ++x + 1;
Run Code Online (Sandbox Code Playgroud)
那么,如果上面的表达式定义得很清楚,那么"命运"是什么呢?
array[x] = ++x;
Run Code Online (Sandbox Code Playgroud)
似乎没有定义后增量和后减量的评估,但定义了预增量和预减量.
注意:这不用于实际代码中.Clang 3.4和GCC 4.8明确警告了增量前后序列点.